<script setup lang="ts">
import { ref, reactive, computed, watch, watchEffect, toRefs } from 'vue'

// 关卡1：ref - 基本类型响应式数据
const hp = ref(100)          // 英雄血量
const attacking = ref(false) // 是否正在攻击

const attack = () => {
  attacking.value = true
  setTimeout(() => {
    hp.value -= 20
    attacking.value = false
  }, 500)
}

// 关卡2：reactive - 对象响应式数据
interface Hero {
  name: string
  level: number
  skills: string[]
}

const hero = reactive<Hero>({
  name: 'Vue 法师',
  level: 1,
  skills: ['火球术']
})

const { name, level } = toRefs(hero)

const levelUp = () => {
  level.value++
  if (level.value === 3) hero.skills.push('冰冻术')
}

// 关卡3：computed - 计算属性
const price = ref(25)
const quantity = ref(2)
const discount = ref(0.8)

const total = computed<number>(() => {
  return price.value * quantity.value * discount.value
})

const add = () => quantity.value++

// 关卡4：watch - 监听数据变化
const id = ref(1)
const data = ref<any>(null)

watch(id, async (newId, oldId) => {
  console.log(`ID 从 ${oldId} → ${newId}`)
  try {
    const res = await fetch(`https://jsonplaceholder.typicode.com/todos/${newId}`)
    data.value = await res.json()
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}, { immediate: true })

const nextId = () => id.value++

// 关卡4：watchEffect - 自动收集依赖
const x = ref(0)
const y = ref(0)

watchEffect(() => {
  console.log(`角色坐标：(${x.value}, ${y.value})`)
})

const updateCoordinates = (event: MouseEvent) => {
  x.value = event.clientX
  y.value = event.clientY
}

// 关卡7：小作业1 - 温度转换器
const celsius = ref<number>(0)
const fahrenheit = computed<string>(() => {
  return ((celsius.value * 9/5) + 32).toFixed(1)
})

const updateCelsius = (value: string) => {
  celsius.value = parseFloat(value) || 0
}

// 关卡7：小作业2 - 待办列表
interface Todo {
  id: number
  text: string
  completed: boolean
}

const todos = reactive<Todo[]>([
  { id: 1, text: '学习Vue3响应式', completed: false },
  { id: 2, text: '掌握ref和reactive', completed: false }
])

const newTodoText = ref('')
const remainingCount = computed(() => {
  return todos.filter(todo => !todo.completed).length
})

const addTodo = () => {
  if (newTodoText.value.trim()) {
    todos.push({
      id: Date.now(),
      text: newTodoText.value,
      completed: false
    })
    newTodoText.value = ''
  }
}

const toggleTodo = (id: number) => {
  const todo = todos.find(t => t.id === id)
  if (todo) {
    todo.completed = !todo.completed
  }
}
</script>

<template>
  <div class="container">
    <h1>Vue3 响应式魔法学习</h1>
    
    <!-- 关卡1：ref示例 -->
    <section class="level">
      <h2>🌟 关卡1: ref - 勇者血量</h2>
      <h3>勇者血量：{{ hp }}</h3>
      <button @click="attack" :disabled="attacking" class="btn">
        {{ attacking ? '攻击中...' : '发起攻击' }}
      </button>
    </section>
    
    <!-- 关卡2：reactive示例 -->
    <section class="level">
      <h2>🌟 关卡2: reactive - 英雄升级</h2>
      <h3>{{ name }} Lv.{{ level }}</h3>
      <p>技能列表：{{ hero.skills.join('、') }}</p>
      <button @click="levelUp" class="btn">打怪升级</button>
    </section>
    
    <!-- 关卡3：computed示例 -->
    <section class="level">
      <h2>🌟 关卡3: computed - 购物车结算</h2>
      <p>单价：{{ price }} × 数量：{{ quantity }} × 折扣：{{ discount }}</p>
      <h4>应付：{{ total.toFixed(2) }} 元</h4>
      <button @click="add" class="btn">再来一杯</button>
    </section>
    
    <!-- 关卡4：watch示例 -->
    <section class="level">
      <h2>🌟 关卡4: watch - 数据监听</h2>
      <p>当前ID: {{ id }}</p>
      <button @click="nextId" class="btn">获取下一条数据</button>
      <div v-if="data" class="data-display">
        <p>数据: {{ JSON.stringify(data) }}</p>
      </div>
    </section>
    
    <!-- 关卡4：watchEffect示例 -->
    <section class="level">
      <h2>🌟 关卡4: watchEffect - 坐标监控</h2>
      <p @mousemove="updateCoordinates" class="coordinate-area">
        移动鼠标查看坐标: ({{ x }}, {{ y }})
      </p>
    </section>
    
    <!-- 关卡7：小作业1 - 温度转换器 -->
    <section class="level">
      <h2>🌟 关卡7: 温度转换器</h2>
      <div class="converter">
        <div>
          <label>摄氏度:</label>
          <input type="number" :value="celsius" @input="updateCelsius(($event.target as HTMLInputElement).value)" />
        </div>
        <div class="equals">=</div>
        <div>
          <label>华氏度:</label>
          <input type="text" :value="fahrenheit" disabled />
        </div>
      </div>
    </section>
    
    <!-- 关卡7：小作业2 - 待办列表 -->
    <section class="level">
      <h2>🌟 关卡7: 待办列表</h2>
      <p>剩余未完成: {{ remainingCount }}</p>
      <div class="todo-input">
        <input v-model="newTodoText" @keyup.enter="addTodo" placeholder="添加新任务" />
        <button @click="addTodo" class="btn">添加</button>
      </div>
      <ul class="todo-list">
        <li v-for="todo in todos" :key="todo.id" :class="{ completed: todo.completed }">
          <input type="checkbox" :checked="todo.completed" @change="toggleTodo(todo.id)" />
          <span>{{ todo.text }}</span>
        </li>
      </ul>
    </section>
  </div>
</template>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
  color: #42b883;
  margin-bottom: 40px;
}

.level {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.level h2 {
  color: #35495e;
  border-bottom: 2px solid #42b883;
  padding-bottom: 10px;
  margin-top: 0;
}

.btn {
  background-color: #42b883;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn:hover:not(:disabled) {
  background-color: #35495e;
}

.btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.coordinate-area {
  background-color: #e3f2fd;
  padding: 40px;
  text-align: center;
  cursor: crosshair;
  border-radius: 4px;
}

.data-display {
  margin-top: 10px;
  background-color: #e9ecef;
  padding: 10px;
  border-radius: 4px;
  font-family: monospace;
}

.converter {
  display: flex;
  align-items: center;
  gap: 20px;
  margin: 20px 0;
}

.converter > div {
  flex: 1;
}

.converter input {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.equals {
  font-size: 24px;
  font-weight: bold;
  color: #35495e;
}

.todo-input {
  display: flex;
  gap: 10px;
  margin: 15px 0;
}

.todo-input input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.todo-list {
  list-style: none;
  padding: 0;
}

.todo-list li {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.todo-list li input[type="checkbox"] {
  margin-right: 10px;
}

.todo-list li.completed span {
  text-decoration: line-through;
  color: #888;
}
</style>